package com.bluetooth.heartchecked.util;


import com.bluetooth.heartchecked.bean.Data;

public class DataUtil {

    public static int getHeartValue(byte[] bytes) {
        Data data = new Data(bytes);
        if (data.size() < 2) {
            return 0;
        }

        // Read flags
        int offset = 0;
        final int flags = data.getIntValue(Data.FORMAT_UINT8, offset);
        final int hearRateType = (flags & 0x01) == 0 ? Data.FORMAT_UINT8 : Data.FORMAT_UINT16;
        final boolean energyExpandedPresent = (flags & 0x08) != 0;
        final boolean rrIntervalsPresent = (flags & 0x10) != 0;
        offset += 1;

        // Validate packet length
        if (data.size() < 1 + (hearRateType & 0x0F)
                + (energyExpandedPresent ? 2 : 0)
                + (rrIntervalsPresent ? 2 : 0)) {
//            onInvalidDataReceived(device, data);
            return -1;
        }

        final int heartRate = data.getIntValue(hearRateType, offset);

        return heartRate;
    }

    public static int getHeartValue2(byte[] bytes) {
        Data data = new Data(bytes);
        if (data.size() < 2) {
            return 0;
        }

        int index = ((bytes[0] & 0x01) == 1) ? 2 : 1;
        int format = (index == 1) ? Data.FORMAT_UINT8 : Data.FORMAT_UINT16;
        int value = data.getIntValue(format, index);

        return value;
    }

    public static String byte2Hex(byte[] data) {
        final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
        if(data == null){
            return "";
        }
        final int length = data.length;
        if(length == 0){
            return "";
        }

        char[] hexChars = new char[data.length * 2];
        for ( int j = 0; j < data.length; j++ ) {
            int v = data[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }

    public static int hex2Int(String hex) {
        try {
            //1900000000,去掉16进制数末尾0
            hex = hex.replaceAll("(0)+$", "");
            return Integer.parseInt(hex, 16);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
